home *** CD-ROM | disk | FTP | other *** search
/ Enter Special 5: Digital Photography / ENTER Special 05.iso / Grafika / Paint Shop Pro 8.0 / psp800ev.exe / Data1.cab / warnings.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  10.4 KB  |  316 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Python part of the warnings subsystem.'''
  5. import sys
  6. import re
  7. import types
  8. __all__ = [
  9.     'warn',
  10.     'showwarning',
  11.     'formatwarning',
  12.     'filterwarnings',
  13.     'resetwarnings']
  14. defaultaction = 'default'
  15. filters = []
  16. onceregistry = { }
  17.  
  18. def warn(message, category = None, stacklevel = 1):
  19.     '''Issue a warning, or maybe ignore it or raise an exception.'''
  20.     if category is None:
  21.         category = UserWarning
  22.     
  23.     if not __debug__ and issubclass(category, Warning):
  24.         raise AssertionError
  25.     
  26.     try:
  27.         caller = sys._getframe(stacklevel)
  28.     except ValueError:
  29.         globals = sys.__dict__
  30.         lineno = 1
  31.  
  32.     globals = caller.f_globals
  33.     lineno = caller.f_lineno
  34.     if globals.has_key('__name__'):
  35.         module = globals['__name__']
  36.     else:
  37.         module = '<string>'
  38.     filename = globals.get('__file__')
  39.     if filename:
  40.         fnl = filename.lower()
  41.         if fnl.endswith('.pyc') or fnl.endswith('.pyo'):
  42.             filename = filename[:-1]
  43.         
  44.     elif module == '__main__':
  45.         filename = sys.argv[0]
  46.     
  47.     if not filename:
  48.         filename = module
  49.     
  50.     registry = globals.setdefault('__warningregistry__', { })
  51.     warn_explicit(message, category, filename, lineno, module, registry)
  52.  
  53.  
  54. def warn_explicit(message, category, filename, lineno, module = None, registry = None):
  55.     if module is None:
  56.         module = filename
  57.         if module[-3:].lower() == '.py':
  58.             module = module[:-3]
  59.         
  60.     
  61.     if registry is None:
  62.         registry = { }
  63.     
  64.     key = (message, category, lineno)
  65.     if registry.get(key):
  66.         return None
  67.     
  68.     for item in filters:
  69.         (action, msg, cat, mod, ln) = item
  70.         if msg.match(message) and issubclass(category, cat) and mod.match(module) and ln == 0 or lineno == ln:
  71.             break
  72.         
  73.     else:
  74.         action = defaultaction
  75.     if action == 'ignore':
  76.         registry[key] = 1
  77.         return None
  78.     
  79.     if action == 'error':
  80.         raise category(message)
  81.     
  82.     if action == 'once':
  83.         registry[key] = 1
  84.         oncekey = (message, category)
  85.         if onceregistry.get(oncekey):
  86.             return None
  87.         
  88.         onceregistry[oncekey] = 1
  89.     elif action == 'always':
  90.         pass
  91.     elif action == 'module':
  92.         registry[key] = 1
  93.         altkey = (message, category, 0)
  94.         if registry.get(altkey):
  95.             return None
  96.         
  97.         registry[altkey] = 1
  98.     elif action == 'default':
  99.         registry[key] = 1
  100.     else:
  101.         raise RuntimeError('Unrecognized action (%s) in warnings.filters:\n %s' % (`action`, str(item)))
  102.     showwarning(message, category, filename, lineno)
  103.  
  104.  
  105. def showwarning(message, category, filename, lineno, file = None):
  106.     '''Hook to write a warning to a file; replace if you like.'''
  107.     if file is None:
  108.         file = sys.stderr
  109.     
  110.     file.write(formatwarning(message, category, filename, lineno))
  111.  
  112.  
  113. def formatwarning(message, category, filename, lineno):
  114.     '''Function to format a warning the standard way.'''
  115.     import linecache
  116.     s = '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)
  117.     line = linecache.getline(filename, lineno).strip()
  118.     if line:
  119.         s = s + '  ' + line + '\n'
  120.     
  121.     return s
  122.  
  123.  
  124. def filterwarnings(action, message = '', category = Warning, module = '', lineno = 0, append = 0):
  125.     '''Insert an entry into the list of warnings filters (at the front).
  126.  
  127.     Use assertions to check that all arguments have the right type.'''
  128.     if not __debug__ and action in ('error', 'ignore', 'always', 'default', 'module', 'once'):
  129.         raise AssertionError, 'invalid action: %s' % `action`
  130.     if not __debug__ and isinstance(message, types.StringType):
  131.         raise AssertionError, 'message must be a string'
  132.     if not __debug__ and isinstance(category, types.ClassType):
  133.         raise AssertionError, 'category must be a class'
  134.     if not __debug__ and issubclass(category, Warning):
  135.         raise AssertionError, 'category must be a Warning subclass'
  136.     if not __debug__ and type(module) is types.StringType:
  137.         raise AssertionError, 'module must be a string'
  138.     if __debug__:
  139.         if not type(lineno) is types.IntType and lineno >= 0:
  140.             raise AssertionError, 'lineno must be an int >= 0'
  141.     item = (action, re.compile(message, re.I), category, re.compile(module), lineno)
  142.     if append:
  143.         filters.append(item)
  144.     else:
  145.         filters.insert(0, item)
  146.  
  147.  
  148. def resetwarnings():
  149.     '''Reset the list of warnings filters to its default state.'''
  150.     filters[:] = []
  151.  
  152.  
  153. class _OptionError(Exception):
  154.     '''Exception used by option processing helpers.'''
  155.     pass
  156.  
  157.  
  158. def _processoptions(args):
  159.     for arg in args:
  160.         
  161.         try:
  162.             _setoption(arg)
  163.         except _OptionError:
  164.             msg = None
  165.             print >>sys.stderr, 'Invalid -W option ignored:', msg
  166.  
  167.     
  168.  
  169.  
  170. def _setoption(arg):
  171.     parts = arg.split(':')
  172.     if len(parts) > 5:
  173.         raise _OptionError('too many fields (max 5): %s' % `arg`)
  174.     
  175.     while len(parts) < 5:
  176.         parts.append('')
  177.     (action, message, category, module, lineno) = [ s.strip() for s in parts ]
  178.     action = _getaction(action)
  179.     message = re.escape(message)
  180.     category = _getcategory(category)
  181.     module = re.escape(module)
  182.     if lineno:
  183.         
  184.         try:
  185.             lineno = int(lineno)
  186.             if lineno < 0:
  187.                 raise ValueError
  188.         except (ValueError, OverflowError):
  189.             None if module else []
  190.             None if module else []
  191.             raise _OptionError('invalid lineno %s' % `lineno`)
  192.         except:
  193.             None if module else []
  194.  
  195.     else:
  196.         lineno = 0
  197.     filterwarnings(action, message, category, module, lineno)
  198.  
  199.  
  200. def _getaction(action):
  201.     if not action:
  202.         return 'default'
  203.     
  204.     if action == 'all':
  205.         return 'always'
  206.     
  207.     for a in [
  208.         'default',
  209.         'always',
  210.         'ignore',
  211.         'module',
  212.         'once',
  213.         'error']:
  214.         if a.startswith(action):
  215.             return a
  216.         
  217.     
  218.     raise _OptionError('invalid action: %s' % `action`)
  219.  
  220.  
  221. def _getcategory(category):
  222.     if not category:
  223.         return Warning
  224.     
  225.     if re.match('^[a-zA-Z0-9_]+$', category):
  226.         
  227.         try:
  228.             cat = eval(category)
  229.         except NameError:
  230.             raise _OptionError('unknown warning category: %s' % `category`)
  231.  
  232.     else:
  233.         i = category.rfind('.')
  234.         module = category[:i]
  235.         klass = category[i + 1:]
  236.         
  237.         try:
  238.             m = __import__(module, None, None, [
  239.                 klass])
  240.         except ImportError:
  241.             raise _OptionError('invalid module name: %s' % `module`)
  242.  
  243.         
  244.         try:
  245.             cat = getattr(m, klass)
  246.         except AttributeError:
  247.             raise _OptionError('unknown warning category: %s' % `category`)
  248.  
  249.     if not isinstance(cat, types.ClassType) or not issubclass(cat, Warning):
  250.         raise _OptionError('invalid warning category: %s' % `category`)
  251.     
  252.     return cat
  253.  
  254.  
  255. def _test():
  256.     import getopt
  257.     testoptions = []
  258.     
  259.     try:
  260.         (opts, args) = getopt.getopt(sys.argv[1:], 'W:')
  261.     except getopt.error:
  262.         msg = None
  263.         print >>sys.stderr, msg
  264.         return None
  265.  
  266.     for o, a in opts:
  267.         testoptions.append(a)
  268.     
  269.     
  270.     try:
  271.         _processoptions(testoptions)
  272.     except _OptionError:
  273.         msg = None
  274.         print >>sys.stderr, msg
  275.         return None
  276.  
  277.     for item in filters:
  278.         print item
  279.     
  280.     hello = 'hello world'
  281.     warn(hello)
  282.     warn(hello)
  283.     warn(hello)
  284.     warn(hello)
  285.     warn(hello, UserWarning)
  286.     warn(hello, DeprecationWarning)
  287.     for i in range(3):
  288.         warn(hello)
  289.     
  290.     filterwarnings('error', '', Warning, '', 0)
  291.     
  292.     try:
  293.         warn(hello)
  294.     except Exception:
  295.         msg = None
  296.         print 'Caught', msg.__class__.__name__ + ':', msg
  297.  
  298.     print 'No exception'
  299.     resetwarnings()
  300.     
  301.     try:
  302.         filterwarnings('booh', '', Warning, '', 0)
  303.     except Exception:
  304.         msg = None
  305.         print 'Caught', msg.__class__.__name__ + ':', msg
  306.  
  307.     print 'No exception'
  308.  
  309. if __name__ == '__main__':
  310.     import __main__
  311.     sys.modules['warnings'] = __main__
  312.     _test()
  313. else:
  314.     _processoptions(sys.warnoptions)
  315.     filterwarnings('ignore', category = OverflowWarning, append = 1)
  316.